package com.example.demo.controller;

import com.example.demo.entity.Instrument;
import com.example.demo.entity.Music;
import com.example.demo.service.InstrumentService;
import com.example.demo.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/instruments")
public class InstrumentController {

    @Autowired
    private InstrumentService instrumentService;

    @GetMapping("/hot")
    public List<Instrument> getHotInstruments() {
        return instrumentService.getHotInstruments();
    }

    @PostMapping("/upload")
    public String getPicFileName(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf('.'));
        String filePath = FileUtil.getUploadFilePath();
        System.out.println(typeName);
        String newFileName = System.currentTimeMillis()+typeName;

        try {
            FileUtil.uploadFile(file.getBytes(),filePath,newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

    @PostMapping
    public ResponseEntity<Void> addInstrument(@RequestBody Instrument instrument) {
        instrumentService.addInstrument(instrument);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateInstrument(@PathVariable("id") Integer id, @RequestBody Instrument instrument) {
        instrument.setInstrument_id(id);
        instrumentService.updateInstrument(instrument);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteInstrument(@PathVariable("id") Integer id) {
        instrumentService.deleteInstrument(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Instrument> getInstrumentById(@PathVariable("id") Integer id) {
        // 增加浏览量
        instrumentService.incrementViewCount(id);
        // 获取乐器详情
        Instrument instrument = instrumentService.getInstrumentById(id);
        return ResponseEntity.ok(instrument);
    }

    @GetMapping
    public ResponseEntity<List<Instrument>> getAllInstruments() {
        List<Instrument> instruments = instrumentService.getAllInstruments();
        return ResponseEntity.ok(instruments);
    }


    @GetMapping("/search")
    public ResponseEntity<List<Instrument>> searchInstruments(@RequestParam("name") String name) {
        List<Instrument> instruments = instrumentService.searchInstruments(name);
        return ResponseEntity.ok(instruments);
    }
}